package com.wyl.mine.collection

import android.view.View
import android.widget.TextView
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.wuhenzhizao.titlebar.widget.CommonTitleBar
import com.wyl.base.CollectionPage
import com.wyl.base.bean.VideoData
import com.wyl.base.openVideoDetailPage
import com.wyl.libbase.base.BindingActivity
import com.wyl.libbase.binding.recyclerview.RecyclerViewSpace
import com.wyl.mine.R
import com.wyl.mine.databinding.CollectionActivityBinding
import com.wyl.mine.databinding.CollectionItemChildBinding
import io.ditclear.bindingadapter.BindingViewHolder
import io.ditclear.bindingadapter.ItemClickPresenter
import io.ditclear.bindingadapter.ItemDecorator
import io.ditclear.bindingadapter.SingleTypeAdapter
import org.koin.android.viewmodel.ext.android.viewModel

@Route(path = CollectionPage)
class CollectionActivity : BindingActivity<CollectionActivityBinding>(), ItemClickPresenter<VideoData>, ItemDecorator {
    private val viewModel: CollectionViewModel by viewModel()

    override fun getLayoutId(): Int = R.layout.collection_activity

    private val mLayoutManager by lazy { LinearLayoutManager(this) }

    private val mDivider by lazy { RecyclerViewSpace() }

    private val mAdapter by lazy {
        SingleTypeAdapter(this, R.layout.collection_item_child, viewModel.dataSource)
            .apply {
                itemPresenter = this@CollectionActivity
                itemDecorator = this@CollectionActivity
            }
    }

    override fun decorator(holder: BindingViewHolder<ViewDataBinding>, position: Int, viewType: Int) {
        val binding = holder.binding as CollectionItemChildBinding
        binding.operation = viewModel.operationVisibable
        if (position == 0) return
        if (viewModel.dataSource[position - 1].group == binding.item?.group) {
            binding.group.visibility = View.GONE
        }
    }

    override fun onItemClick(v: View, item: VideoData) {
        if (viewModel.isOperation) {
            item.selected = !item.selected
        } else {
            openVideoDetailPage(item.appFolkOperaId)
        }
    }

    override fun initView() {
        binding.vm = viewModel

        binding.titlebar.setListener { view, action, _ ->
            when (action) {
                CommonTitleBar.ACTION_LEFT_BUTTON -> onBackPressed()
                CommonTitleBar.ACTION_RIGHT_TEXT -> {
                    viewModel.operation()
                    (view as TextView).text = viewModel.operation.get()
                }
                else -> {
                }
            }
        }

        binding.include.recyclerView.apply {
            layoutManager = mLayoutManager
            adapter = mAdapter
            addItemDecoration(mDivider)
        }

    }

    override fun loadData() {
        viewModel.refresh()
    }

}
